package friot.service.cloud.service;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import friot.model.iot.entity.IotThings;
import friot.model.iot.vo.IotDeviceVo;
import friot.service.cloud.mapper.IotThingsMapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * (IotThings)表服务实现类
 *
 * @author makejava
 * @since 2024-03-14 14:21:12
 */
@Service("iotThingsService")
public class IotThingsServiceImpl extends ServiceImpl<IotThingsMapper, IotThings> implements IotThingsService {

    @Resource
    private IotDeviceService iotDeviceService;

    /**
     * 根据用户ID查询设备日志
     *
     * @param userId 用户ID
     * @return 设备日志
     */
    @Override
    public List<IotThings> listThingsByUserId(int userId) {
        // 获取用户的设备列表
        List<IotDeviceVo> iotDeviceVos = iotDeviceService.listAndMapByUserId(userId);
        List<String> deviceIds = iotDeviceVos.stream().map(IotDeviceVo::getDeviceId).collect(Collectors.toList());

        // 获取设备日志
        LambdaQueryWrapper<IotThings> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(IotThings::getDeviceId, deviceIds).orderByDesc(IotThings::getCreateTime);
        return list(wrapper);
    }

    /**
     * 根据条件查询设备日志
     *
     * @param deviceId   设备ID
     * @param identified 设备标识
     * @param num        查询条数
     * @return 设备日志
     */
    @Override
    public List<IotThings> listThingsByCondition(String deviceId, String identified, Integer num) {
        return lambdaQuery().eq(IotThings::getDeviceId, deviceId)
                .eq(IotThings::getIdentified, identified)
                .orderByDesc(IotThings::getCreateTime)
                .last("limit " + num)
                .list();
    }
}

